package com.dycloud.project.service.impl;

import com.dycloud.project.constant.CacheConstants;
import com.dycloud.project.domain.UserLikeRecord;
import com.dycloud.project.event.LikeEvent;
import com.dycloud.project.security.LoginUser;
import com.dycloud.project.service.IUserLikeRecordService;
import com.dycloud.project.service.UserLikeService;
import com.dycloud.project.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : renhang
 * @description UserLikeServiceImpl
 * @date : 2025-07-02 23:45
 **/
@Service
@Slf4j
public class UserLikeServiceImpl implements UserLikeService {
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    IUserLikeRecordService userLikeRecordService;


    @Override
    public void like(String targetType, Long id, Integer likeStatus) {
        // 根据类型+id 加锁， 根据id+user+type(行业动态)生成一条点赞记录
        RLock lock = redissonClient.getLock(String.format(CacheConstants.LIKE_LOCK_KEY, targetType, id));
        try {
            // 尝试加锁3秒
            boolean isLocked = lock.tryLock(3, TimeUnit.SECONDS);
            if (isLocked) {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                // 详情可以看 LikeEventListener
                applicationContext.publishEvent(LikeEvent.builder().userId(loginUser.getUserId()).username(loginUser.getUser().getNickName()).targetType(targetType)
                        .id(id).likeStatus(likeStatus).build());
            } else {
                // 获取锁失败
                log.warn("未能获取锁，跳过此次点赞统计");
            }
        } catch (InterruptedException e) {
            log.warn("like Warn! tryLock fail");
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }

    @Override
    public Integer getLikeStatus(String targetType, Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 类型+userId+id 查询
        UserLikeRecord userLikeRecord = userLikeRecordService.queryUserIsLiked(targetType, id, loginUser.getUserId());
        return Objects.nonNull(userLikeRecord) ? 1 : 0;
    }
}
